<template
  ><div>
    <a-tabs v-model="activeKey" tab-position="top" @tabClick="tabClick" @prevClick="prevClick" @nextClick="nextClick">
      <a-tab-pane v-for="item in this.stepList" :tab="item.name" :key="item.id"> </a-tab-pane>
    </a-tabs>
    <k-form-design
      ref="formDesign"
      title="表单设计"
      toolbarsTop
      :toolbars="['preview', 'exportJson', 'importJson']"
      :showHead="false"
    />
  </div>
</template>
<script>
import { findTable, findAll } from '@/api/base/table.js'
import { DATA_BASE_SFAPPROVE } from '@/store/mutation-types.js'
import { setTreeList } from '@/utils/formassembly/generaltree.js'
import jsonFormat from '../../components/k-form-design/packages/KFormDesign/config/jsonFormat'
export default {
  props: {
    // 流程环节列表
    stepList: {
      type: Array
    },
    formInfo: {
      type: Object,
      default: () => null
    },
    form: {}
  },
  data() {
    return {
      activeKey: null, // 当前激活的tab
      layout: {
        id: null,
        formid_: null,
        type_: null,
        layout_: null
      }
    }
  },
  watch: {
    'formInfo.step4.layout': {
      handler(v) {
        // console.log('watch formInfo.step4.layout', v)
        // 当前环节没有配置过, 则进行配置初始化
        if (v == null) {
          this.layout.id = this.layout.primaryKey =  null
          this.layout.type_ = 90500
          this.layout.formid_ = this.formInfo.formid
          this.layout.layout_ = jsonFormat
          this.layout.stepid_ = this.activeKey
        } else {
          // 配置过来更新对应的key
          Object.keys(v).forEach(key => {
            this.layout[key] = v[key]
          })
        }
        // console.log('this.layout', this.layout)
        // 更新界面布局
        this.tabConfigInit()
      },
      // 开启深度监听：只要obj中的任何一个属性发生改变，都会触发相应的代码
      deep: true
    }
  },
  async created() {
    if (this.formInfo.step4.layout?.id) {
      Object.keys(this.formInfo.step4.layout).forEach(key => {
        this.layout[key] = this.formInfo.step4.layout[key]
      })
    }
    // 查询流程环节列表
    this.activeKey = this.stepList[0].id
    //  首次初始化
    this.tabClick(this.activeKey)
    this.tabConfigInit()
  },
  methods: {
    // tab标签点击
    async tabClick(key) {
      // 把当前的环节id存到路由里
      this.$route.params.stepid_ = key
      await this.$emit('f_getLayout', key)
    },
    // 上一个
    prevClick(e) {
      // console.log('上一个', e)
    },
    // 下一个
    nextClick(e) {
      // console.log('下一个', e)
    },
    // tab配置器初始化
    tabConfigInit() {
      let layoutJSON = null
      let pkArr = []
      let tableName = []
      if (this.layout.layout_) {
        //   console.log('mounted this.layout.layout_', this.layout)
        layoutJSON = JSON.parse(this.layout.layout_)
        // 给组件 / 表单配置器赋值
        layoutJSON = JSON.parse(this.layout.layout_)
        // console.log('layoutJSON', layoutJSON)

        this.$store.commit('setOriginal', layoutJSON?.componentJson?.originalObj || null)
        this.$store.commit('setAnalysis', layoutJSON?.componentJson?.analysisObj || null)
        this.$store.commit(
          'setFormObj',
          layoutJSON?.formJson?.formObj && JSON.stringify(layoutJSON.formJson.formObj) != '{}'
            ? layoutJSON.formJson.formObj
            : null
        )
        // 回显树配置
        setTreeList(layoutJSON.treeList || [])

        console.log('JSON转对象', layoutJSON)
        pkArr = this.getFieldSchema(layoutJSON.list, true).map(m => m.pk)
        tableName = pkArr.map(m => m.split('#')[0])
      }
      if (this.formInfo.step3.data && this.formInfo.step3.data.length) {
        var data = JSON.parse(JSON.stringify(this.formInfo.step3.data))
        //   console.log(tableName, 'data', data)
        data.forEach(table => {
          if (tableName.includes(table.tabname_)) {
            table.fields.forEach(field => {
              field.disabled = pkArr.includes(table.tabname_ + '#' + field.fieldName)
            })
          }
        })
        // 字段绑定弹框数据赋值
        this.$nextTick(() => {
          // console.log('this.$refs.formDesign.handleSetTableData', this.$refs.formDesign.handleSetTableData)
          this.$refs.formDesign.handleSetTableData(data)
        })
        
        this.handleList(JSON.parse(JSON.stringify(data)))
      }
      if(this.$refs.formDesign) {
        layoutJSON && this.$refs.formDesign.handleSetData(layoutJSON)
      }
      
    },
    // 处理选中的数据表字段
    handleList(list) {
      if (typeof list !== 'object') {
        return
      }
      let listCopy = []
      list.forEach(item => {
        if (item.fields?.length) {
          item.fields.forEach(filed => {
            if (filed.disabled) {
              listCopy.push({
                title: `${filed.tableName}#${filed.fieldName}`,
                value: `${filed.tableName}#${filed.fieldName}`
              })
            }
          })
        }
      })
      listCopy.push({
        title: '填充值',
        value: 'fill'
      })
      this.$store.commit('setListData', listCopy)
    },
    // 获取字段架构
    getFieldSchema(data, hasPk) {
      const fields = []
      const traverse = array => {
        array.forEach(element => {
          if (element.type === 'grid' || element.type === 'tabs') {
            // 栅格布局
            element.columns.forEach(item => {
              traverse(item.list)
            })
          } else if (element.type === 'card') {
            // 卡片布局
            traverse(element.list)
          } else if (element.type === 'batch') {
            // 动态表格内复制
            traverse(element.list)
          } else if (element.type === 'table') {
            // 表格布局
            element.trs.forEach(item => {
              item.tds.forEach(val => {
                traverse(val.list)
              })
            })
          } else {
            const condition = hasPk ? element.pk : !element.pk
            // console.log('element', element, element.model && !element.pk)
            if (element.model && condition) {
              fields.push(element)
            }
          }
        })
      }
      traverse(data)
      return fields
    },
    validate() {
      const data = JSON.parse(JSON.stringify(this.$refs.formDesign.data))
      //   console.log('json', data)
      if (!data?.list?.length) {
        this.$message.warning('请至少选择一个组件')
        return false
      }
      const fields = this.getFieldSchema(data.list, false)
      //   console.log('fields', fields)
      if (fields.length) {
        this.$message.warning(`请为${fields[0].label}等${fields.length}个组件关联表字段!`)
        this.$refs.formDesign.handleSetSelectItem(fields[0])
        return false
      }
      return true
    },
    setData() {
      const layout = JSON.parse(JSON.stringify(this.$refs.formDesign.data))
      this.layout.layout_ = layout
      //   console.log('layout json', this.layout.layout_)
      this.$emit('setData', this.layout)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ant-modal {
  width: 1200px !important;
}

/deep/.ant-modal-content {
  width: 1200px;
  max-height: 800px;
  overflow: auto;
}
</style>
